import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  const userInfo = store.getters.userInfo

  if (hasToken) {
    if (userInfo) {
      // 如果有用户信息,则判断是否区login页面
      if (to.path.includes('/login')) {
        // 如果是的话,则跳转回之前的页面
        next(from.path)
        Message.info('请勿重复登录')
        NProgress.done()
      } else {
        // 如果不是,则直接跳转
        next()
      }
    } else {
      // 如果没有用户信息则请求
      try {
        // 尝试请求用户信息,如果没错则放行
        await store.dispatch('user/getInfo')
        next()
      } catch (error) {
        // 如果请求失败,则删除token,并且返回登录页
        Message.warning('用户身份过期,请重新登陆')
        removeToken()
        next(`/login?redirect=${to.path}`)
      }
    }
  } else {
    /* has no token*/

    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // Message.info('请先登录')
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
